﻿using HandyControl.Controls;
using Infov1.Commands;
using Infov1.Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Infov1.ViewModels
{
    public class CustomerCategoryViewModel : ViewModelBase
    {
        // 数据库访问对象
        private readonly ISqlSugarClient _db;
        // 类别列表集合
        private ObservableCollection<CustomerCategoryModel> _categoryList;
        // 编辑标志
        private bool _isEditing;
        // 选中项
        private CustomerCategoryModel _selectedCategory;
        // 是否为新增模式
        private bool _isNewMode;
        // 编辑时保存原编码
        private string _oldCategoryCode;

        /// <summary>
        /// 构造函数：初始化数据库连接并加载数据
        /// </summary>
        public CustomerCategoryViewModel()
        {
            _db = DbContext.GetConnection();
            LoadCategoryCommand = new RelayCommand(LoadCategories);
            AddNewCommand = new RelayCommand(AddNew);
            SaveCommand = new RelayCommand(Save);
            StartEditCommand = new RelayCommand(StartEdit);
            DeleteCommand = new RelayCommand(Delete);
            RefreshCommand = new RelayCommand(Refresh);
            // 加载数据
            LoadCategories();
        }

        // 命令属性
        public ICommand LoadCategoryCommand { get; }
        public ICommand AddNewCommand { get; }
        public ICommand SaveCommand { get; }
        public ICommand StartEditCommand { get; }
        public ICommand DeleteCommand { get; }
        public ICommand RefreshCommand { get; }

        // 属性定义
        public ObservableCollection<CustomerCategoryModel> CategoryList
        {
            get => _categoryList;
            set
            {
                _categoryList = value;
                OnPropertyChanged(nameof(CategoryList));
            }
        }

        public bool IsEditing
        {
            get => _isEditing;
            set
            {
                _isEditing = value;
                OnPropertyChanged(nameof(IsEditing));
            }
        }

        public CustomerCategoryModel SelectedCategory
        {
            get => _selectedCategory;
            set
            {
                _selectedCategory = value;
                OnPropertyChanged(nameof(SelectedCategory));
            }
        }

        /// <summary>
        /// 加载类别数据
        /// </summary>
        private void LoadCategories()
        {
            IsEditing = false;
            _isNewMode = false;
            if (_db == null) return;

            var categories = _db.Queryable<CustomerCategoryModel>().ToList();
            CategoryList = new ObservableCollection<CustomerCategoryModel>(categories);
        }

        /// <summary>
        /// 新增类别
        /// </summary>
        private void AddNew()
        {
            IsEditing = true;
            _isNewMode = true;
            SelectedCategory = null;
            CategoryList = new ObservableCollection<CustomerCategoryModel>
                {
                    new CustomerCategoryModel()
                };
        }

        /// <summary>
        /// 保存类别
        /// </summary>
        private void Save()
        {
            if (!IsEditing) return;

            var category = CategoryList.FirstOrDefault();
            if (category == null) return;

            if (string.IsNullOrEmpty(category.CategoryCode))
            {
                Growl.Warning("请输入有效编码,必须大于0！");
                return;
            }

            if (!int.TryParse(category.CategoryCode.ToString(), out int codeValue) || codeValue <= 0)
            {
                Growl.Warning("请输入有效编码,必须大于0！");
                return;
            }

            if (string.IsNullOrWhiteSpace(category.CategoryName))
            {
                Growl.Warning("类别名称不能为空！");
                return;
            }

            try
            {
                if (_isNewMode)
                {
                    var exists = _db.Queryable<CustomerCategoryModel>()
                        .Any(x => x.CategoryCode == category.CategoryCode);
                    if (exists)
                    {
                        Growl.Warning("类别编码已存在！");
                        return;
                    }

                    if (category.CategoryCode.Length != 2)
                    {
                        Growl.Warning("类别编码必须为两位！");
                        return;
                    }

                    _db.Insertable(category).ExecuteCommand();
                    Growl.Success("新增成功！");
                }
                else
                {
                    if (category.CategoryCode != _oldCategoryCode)
                    {
                        Growl.Warning("类别编码不允许修改！");
                        return;
                    }

                    _db.Updateable(category).ExecuteCommand();
                    Growl.Success("更新成功！");
                }
            }
            catch (Exception ex)
            {
                Growl.Error($"保存失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 开始编辑
        /// </summary>
        private void StartEdit()
        {
            if (SelectedCategory == null || string.IsNullOrWhiteSpace(SelectedCategory.CategoryCode))
            {
                Growl.Warning("请选择要编辑的类别！");
                return;
            }

            _oldCategoryCode = SelectedCategory.CategoryCode;
            IsEditing = true;
            _isNewMode = false;

            CategoryList = new ObservableCollection<CustomerCategoryModel>
        {
            new CustomerCategoryModel
            {
                CategoryCode = SelectedCategory.CategoryCode,
                CategoryName = SelectedCategory.CategoryName
            }
        };
        }

        /// <summary>
        /// 删除类别
        /// </summary>
        private void Delete()
        {
            if (_isNewMode || _isEditing)
            {
                Growl.Warning("此模式下不允许删除！");
                return;
            }
            
            if (SelectedCategory == null)
            {
                Growl.Warning("请选择要删除的内容！");
                return;
            }
            // 弹出确认对话框
            MessageBoxResult result = HandyControl.Controls.MessageBox.Show(
                "确定要删除所选类别吗？",
                "确认删除",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            // 如果用户选择不删除或关闭了对话框，则返回
            if (result != MessageBoxResult.Yes)
            {
                return;
            }
            try
            {
                _db.Deleteable<CustomerCategoryModel>()
                    .Where(x => x.CategoryCode == SelectedCategory.CategoryCode)
                    .ExecuteCommand();

                LoadCategories();
                _isNewMode = false;
                SelectedCategory = null;
                Growl.Success("删除成功！");
            }
            catch (Exception ex)
            {
                Growl.Error($"删除失败：{ex.Message}");
            }
        }

        private void Refresh()
        {
            LoadCategories();
        }
    }
}
